const borrowsModule = {
    init() {
        this.loadBorrows();
    },

    loadBorrows() {
        fetch(`${API_BASE_URL}/borrows`)
            .then(response => response.json())
            .then(borrows => {
                const html = `
                    <div class="d-flex justify-content-between align-items-center">
                        <h2>借阅管理</h2>
                        <button type="button" class="btn btn-primary" id="addBorrowBtn">新增借阅</button>
                    </div>
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>读者姓名</th>
                                    <th>图书名称</th>
                                    <th>借阅时间</th>
                                    <th>归还时间</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${borrows.map(borrow => `
                                    <tr>
                                        <td>${borrow.reader?.name || '未知'}</td>
                                        <td>${borrow.book?.title || '未知'}</td>
                                        <td>${new Date(borrow.borrowDate).toLocaleString()}</td>
                                        <td>${borrow.returnDate ? new Date(borrow.returnDate).toLocaleString() : '-'}</td>
                                        <td>
                                            <span class="badge ${borrow.status === 0 ? 'bg-warning' : 'bg-success'}">
                                                ${borrow.status === 0 ? '借出' : '已还'}
                                            </span>
                                        </td>
                                        <td>
                                            ${borrow.status === 0 ? `
                                                <button class="btn btn-sm btn-success return-book" data-id="${borrow.id}">
                                                    归还
                                                </button>
                                            ` : ''}
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                $('#main-content').html(html);

                // 绑定事件
                $('#addBorrowBtn').on('click', () => this.showAddBorrowForm());
                $('.return-book').on('click', (e) => {
                    const borrowId = $(e.target).data('id');
                    this.returnBook(borrowId);
                });
            })
            .catch(handleError);
    },

    showAddBorrowForm() {
        // 获取读者和图书列表
        Promise.all([
            fetch(`${API_BASE_URL}/readers`).then(res => res.json()),
            fetch(`${API_BASE_URL}/books`).then(res => res.json())
        ]).then(([readers, books]) => {
            const html = `
                <div class="form-container">
                    <h3>新增借阅</h3>
                    <form id="addBorrowForm" class="needs-validation" novalidate>
                        <div class="mb-3">
                            <label class="form-label">选择读者</label>
                            <select class="form-select" name="readerId" required>
                                <option value="">请选择读者</option>
                                ${readers.map(reader => `
                                    <option value="${reader.id}">${reader.name} (${reader.cardNumber})</option>
                                `).join('')}
                            </select>
                            <div class="invalid-feedback">请选择读者</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">选择图书</label>
                            <select class="form-select" name="bookId" required>
                                <option value="">请选择图书</option>
                                ${books.filter(book => book.stock > 0).map(book => `
                                    <option value="${book.id}">${book.title} (库存: ${book.stock})</option>
                                `).join('')}
                            </select>
                            <div class="invalid-feedback">请选择图书</div>
                        </div>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">提交</button>
                            <button type="button" class="btn btn-secondary" onclick="borrowsModule.loadBorrows()">返回</button>
                        </div>
                    </form>
                </div>
            `;
            $('#main-content').html(html);

            // 表单验证和提交
            const form = document.getElementById('addBorrowForm');
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                if (!form.checkValidity()) {
                    e.stopPropagation();
                    form.classList.add('was-validated');
                    return;
                }

                const formData = new FormData(e.target);
                const borrow = Object.fromEntries(formData.entries());
                
                fetch(`${API_BASE_URL}/borrows`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(borrow)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('借阅失败，请检查图书库存');
                    }
                    return response.json();
                })
                .then(() => {
                    alert('借阅成功！');
                    this.loadBorrows();
                })
                .catch(handleError);
            });
        }).catch(handleError);
    },

    returnBook(id) {
        if (confirm('确认归还该图书？')) {
            fetch(`${API_BASE_URL}/borrows/${id}/return`, {
                method: 'PUT'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('归还失败');
                }
                alert('归还成功！');
                this.loadBorrows();
            })
            .catch(handleError);
        }
    }
}; 